from typing import List

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        length = len(nums)
        nums.sort()
        cs3 = nums[0] + nums[1] + nums[2]
        prev = None
        for i, vi in enumerate(nums):
            if prev == vi:
                continue
            l = i + 1
            r = length - 1
            while l < r:
                vl, vr = nums[l], nums[r]
                s3 = vi + vl + vr
                if abs(s3 - target) < abs(cs3 - target):
                    cs3 = s3

                if s3 == target:
                    return s3
                elif s3 > target:
                    r -= 1
                else:
                    l += 1
            prev = vi
        return cs3


solu = Solution()
print(solu.threeSumClosest([-1, 2, 1, -4], 1))  # 2
print(solu.threeSumClosest([1, 1, -1, -1, 3], 3))  # 3
print(solu.threeSumClosest([1, 2, 4, 8, 16, 32, 64, 128], 82))  # 82
